package com.qf.java2107.yb.hotel.controller;

import com.qf.java2107.yb.hotel.constant.MethodConstant;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author yb
 * @version 1.0
 * @date 2021-10-26
 **/
public class BaseServlet extends HttpServlet {

    /**
     *
     * 谁在调用service方法?   tomcat
     *      在调用FoodTypeControll的对象的service方法？
     */

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try {

            //获取method请求参数的值
            String methodName = request.getParameter(MethodConstant.METHOD);

            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //反射调用方法
            String responseResult = (String) method.invoke(this, request, response);

            //要跳转的目标资源
            String url = responseResult.substring( responseResult.indexOf(MethodConstant.TAG) + 1);

            if(responseResult.startsWith(MethodConstant.FORWARD_PREFIX)) {
                //转发
                request.getRequestDispatcher(url).forward(request, response);
            } else if(responseResult.startsWith(MethodConstant.REDIRECT_PREFIX)) {
                //重定向
                response.sendRedirect(url);
            } else {
                response.getWriter().write(responseResult);
            }
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.getWriter().write("服务器正忙，请稍后重试！");
    }
}
